package ynet

import (
	"errors"
	"fmt"
	"net"
	"yigo/yiface"
)

type Server struct {
	Name      string
	IP        string
	Port      int
	IPVersion string
	addr      string
}

func toClient(conn *net.TCPConn, data []byte, len int) error {
	fmt.Println("To client")
	_, err := conn.Write(data[:len])
	if err != nil {
		fmt.Println("connection write error : ", err)
		return errors.New("connection write error  ")
	}

}

//
func (o *Server) Start() {
	fmt.Println(fmt.Sprintf("Server %s is starting", o.Name))
	go func() {
		addr, err := net.ResolveTCPAddr(o.IPVersion, fmt.Sprintf("%s:%d", o.IP, o.Port))
		if err != nil {
			fmt.Println("net.ResolveTCPAddr error : ", err)
		}

		listener, err := net.ListenTCP(o.IPVersion, addr)
		if err != nil {
			fmt.Println("net.ListenTCP error : ", err)
		}
		var connID uint32
		connID = 0
		go func() {
			for {
				conn, err := listener.AcceptTCP()
				if err != nil {
					fmt.Println("listener.AcceptTCP error : ", err)
				}

				connService := NewConnection(conn, connID, toClient)
				go connService.Start()
				connID++
			}
		}()
	}()

}

func (o *Server) Stop() {

}

func (o *Server) Serve() {
	o.Start()
	select {}
}

func NewServer() yiface.IServer {
	return &Server{
		Name:      "Yigo",
		IP:        "127.0.0.1",
		IPVersion: "tcp4",
		Port:      999,
	}
}
